package com.huawei.csi.tool.util;

import com.google.gson.Gson;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.lang.reflect.Type;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.*;
import java.util.stream.Stream;

/**
 * @author lxw
 */
public class FileUtil {
    /**
     * LOGGER
     */
    private static final Logger LOGGER = LoggerFactory.getLogger(FileUtil.class);

    private static final ClassLoader CLASSLOADER = FileUtil.class.getClassLoader();

    /**
     * json文件解析成对象
     * Type type = new TypeToken<List<LicenseConfig>>(){}.getType();
     *
     * @param resourceName resourceName
     * @param type         type
     * @return java.util.Optional<java.lang.Object>
     **/
    public static Optional<Object> jsonFile2Class(String resourceName, Type type) {
        Gson gson = new Gson();
        try (InputStream inputStream = CLASSLOADER.getResourceAsStream(resourceName)) {
            if (inputStream == null) {
                LOGGER.info("资源文件未找到: {}", resourceName);
                return Optional.empty();
            }
            InputStreamReader reader = new InputStreamReader(inputStream, StandardCharsets.UTF_8);
            return Optional.of(gson.fromJson(reader, type));
        } catch (IOException e) {
            LOGGER.error("资源文件读取异常: {}", e.getMessage());
        }
        return Optional.empty();
    }


    /**
     * 指定扫描的文件及其文件路径，提供给校验规则使用
     *
     * @param directory directory
     * @param scanFiles scanFiles
     */
    public static Map<String, Path> findRootDirectoryRegularFile(Path directory, List<String> scanFiles) {
        Map<String, Path> validator = new HashMap<>(scanFiles.size() * 2);
        // 遍历目录
        try (Stream<Path> stream = Files.walk(directory)) {
            stream.filter(Files::isRegularFile)
                    .filter(path -> {
                        String pathString = path.toString();
                        pathString = pathString.substring(0, pathString.lastIndexOf("\\"));
                        return pathString.equalsIgnoreCase(directory.toString());
                    })
                    .filter(path -> scanFiles.stream()
                            .anyMatch(s -> s.equalsIgnoreCase(path.getFileName().toString()))) // 忽略大小写
                    .forEach(path -> {
                        validator.put(path.getFileName().toString(), path);
                    });
        } catch (IOException e) {
            LOGGER.error("遍历目录 {} 时出错 exception=：{}", directory, e.getMessage());
        }
        return validator;
    }

    public static List<String> getFileContentList(Path path) {
        List<String> contentList = new ArrayList<>();
        try (Stream<String> stream = Files.lines(path)) {
            stream.forEach(s -> {
                if (s == null || s.trim().isEmpty()) return;
                contentList.add(s.trim());
            });
        } catch (IOException e) {
            LOGGER.error("获取文件内容异常，{}", e.getMessage());
        }
        return contentList;
    }

}
